<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<script type="text/javascript">
   function pwdFocus() {
        $("#waiting").hide()  ;
        $('#fakepassword').hide();
        $('#password').show();
        $('#password').focus();
    }

    function pwdBlur() {
        if ($('#password').attr('value') == '') {
            $("#validPassword").html("");
            $("input[name='isNormal']").val(false);
            $('#password').hide();
            $('#fakepassword').show();
        }else{
            if ($('#password').val().length>=5) {
                var password=$('#password').val();
                         $.ajax({
                                      url:'checkPassword.action',
                                      data:"password="+password,
                                      type:'POST',
                                      dataType:'json' ,
                                           success:function(data){
                                               if(data.result!=""){
                                                  $("#validPassword").text(data.result);
                                                   $("input[name='isNormal']").val(false);
                                               }else{
                                                       $("input[name='isNormal']").val(true);
                                                  var ok="<img src='images/ok/ok.png' width='16' height='16' />"  ;
                                                  $("#validPassword").html(ok);
                                                  cnfPwdBlur();

                                               }
                                             }
                                });
            } else {
                $("#validPassword").html("");
                 $("#validPassword").text("Must include more than 5!");
                $("input[name='isNormal']").val(false);
            }
        }
    }

       function cnfPwdFocus() {
        $('#fakeCnfPassword').hide();
        $('#confirmPassword').show();
        $('#confirmPassword').focus();
    }

    function cnfPwdBlur() {
        if ($('#confirmPassword').attr('value') == '') {
            $("#validCnfPassword").html("");
            $("input[name='isNormal']").val(false);
            $('#confirmPassword').hide();
            $('#fakeCnfPassword').show();
        }   else {
            if($('#password').val()==$('#confirmPassword').val()){
                  $("input[name='isNormal']").val(true);
                   var ok="<img src='images/ok/ok.png' width='16' height='16' />"  ;
                $("#validCnfPassword").html(ok);
            } else {
                $("#validCnfPassword").html("");
                $("#validCnfPassword").text("Doesn't matches with password");
                $("input[name='isNormal']").val(false);
            }
        }
    }

    $(document).ready(function(){
        var  ajaxLoading=false;
        $(".removeUser").hide();
        $(".item").hover(function(){
             $(this).find(".removeUser").show();
          },
          function(){
               $(this).find(".removeUser").hide();
          });
          var valueUserName;

          $('.userName').focus(function() {
              valueUserName = $(this).val();
              if (valueUserName == "Username") {
                  $(this).val("");
              }
          });
          $('.userName').blur(function() {
              if ($(this).val() == "") {
                  $(this).val("Username");
              } else {
                      if ($(this).val().length>=5) {
                            var username= $(this).val();
                                $.ajax({
                                      url:'checkUsername.action',
                                      data:"userName="+username,
                                      type:'POST',
                                      dataType:'json' ,
                                           success:function(data){
                                               if(data.result!=""){
                                                   if(data.result=="login"){
                                                         window.location.href = 'main.action';
                                                    }else{
                                                      $("#validUsername").text(data.result);
                                                       $("input[name='isNormal']").val(false);
                                                   }
                                               }else{
                                                     $("input[name='isNormal']").val(true);
                                                  var ok="<img src='images/ok/ok.png' width='16' height='16' />"  ;
                                                  $("#validUsername").html(ok);
                                               }
                                             }
                                });
                      }  else {
                          $("#validUsername").html("");
                          $("#validUsername").text("Input more than 5 letters!");
                          $("input[name='isNormal']").val(false);
                      }
              }
          });

          var email;
          $('.email').focus(function() {
              email = $(this).val();
              if (email == "Email") {
                  $(this).val("");
              }

          });
          $('.email').blur(function() {
              if ($(this).val() == "") {
                  $(this).val("Email");
              } else{
                 var email=$(this).val();
                         $.ajax({
                              url:'checkEmail.action',
                              data:"email="+email,
                              type:'POST',
                              dataType:'json' ,
                                   success:function(data){

                                       if(data.result!=""){
                                           if(data.result=="login"){
                                                window.location.href = 'main.action';
                                            }else{
                                              $("#validEmail").text(data.result);
                                               $("input[name='isNormal']").val(false);
                                           }
                                       }  else {
                                             $("input[name='isNormal']").val(true);
                                           var ok="<img src='images/ok/ok.png' width='16' height='16' />"  ;
                                           $("#validEmail").html(ok);
                                       }
                                   }
                          });
              }
          });

          if ($("#items").find(".item").length > 0) {
              var firstUser = $("#items").find(".item").first();
              firstUser.find(".eachUserName").addClass("selecting");
              var userId = firstUser.find("input[name='userId']").val();
              $.ajax({
                          url: "viewUserInfo.action",
                          data:"userId=" + userId,
                          type:"post",
                          success:function(data) {
                              $("#deviceInfo").html(data);
                              firstUser.attr({disabled:false});
                              $("input[name='selectedDevice']").val("");
                          }
                      });
          }


        $(".add").live("click",function () {
            var hh = $("#header").height()+ $("#content").height()+ $("#footer").height()+$("#menuLay").height()+2*25+80+2*10;
            $('#grayBox').css({ opacity: 0.7, 'width':"100%",'height':hh});
            $("#addUser").show("slow");

        });


          $("#cancel").click(function(){
               $('#password').hide();
               $('#confirmPassword').hide();
               $('#fakepassword').show();
               $('#fakeCnfPassword').show();
          })

          $(".closeWindow").click(function (e) {
                  $("#addUser").hide("slow");
                  $('#grayBox').css("width", "0px");
                  $('#grayBox').css("height", "0px");
                  return false;
          });

          $(".removeUser").click(function() {
              if(!ajaxLoading){
                  ajaxLoading=true;
                  var userId = $(this).parent().find("input[name='userId']").val();
                  var userName= $(this).find("input[name='userName']").val();
                  if(confirm("Do you really want to remove "+userName+" user?")){
                         $.ajax({
                              url: "removeUser.action",
                              data:"userId=" + userId,
                              type:"post",
                               success:function(data) {

                                 location.reload();
                              }
                          });
                  }
                  ajaxLoading=false;
              }
          });

      $("#cancel").click(function(){
             var changed=false;
              if($(".userName").val()!="" && $(".userName").val()!="Username"){
                  changed=true;
              } else{
                  if($(".email").val()!="" && $(".email").val()!="Email")
                     {
                          changed=true;
                     } else {

                          if($(".managerEmail").val()!="" && $(".managerEmail").val()!="Manager Email"){
                              changed=true;
                          }else
                              if($("#password").val()!="" && $("#password").val()!="Password")
                             {
                                changed=true;
                             }
                     }
              }

              if (!changed) {
                    $("#validUsername").html("");
                    $("#validCnfPassword").html("");
                    $("#validEmail").html("");
                    $("#validPassword").html("");
                    $("input[name='userName']").val("Username");
                    $("input[name='email']").val("Email");
                    $("input[name='password']").val("Password");
                    $("input[name='confirmPassword']").val("Confirm Password");
                    $("#saveUser").attr({disabled:false}) ;
                    $("#addUser").hide("slow");
                    $('#grayBox').css("width", "0px");
                    $('#grayBox').css("height", "0px");
                      $("#waiting").hide() ;
              } else {
                  if (confirm("Do you want to cancel your data?")) {
                        $("#validUsername").html("");
                        $("#validCnfPassword").html("");
                        $("#validEmail").html("");
//                        $("#validManagerEmail").html("");
                        $("#validPassword").html("");
                        $("input[name='userName']").val("Username");
                        $("input[name='email']").val("Email");
//                        $("input[name='managerEmail']").val("Manager Email");
                        $("input[name='password']").val("Password");
                        $("input[name='confirmPassword']").val("Confirm Password");

                        $("#addUser").hide("slow");
                        $('#grayBox').css("width", "0px");
                        $('#grayBox').css("height", "0px");
                           $("#waiting").hide() ;
                          $("#saveUser").attr({disabled:false}) ;
                      return false;
                  }
                  return false;
              }
      })  ;

      $("#saveUser").click(function(){

          if(!ajaxLoading){
              ajaxLoading=true;
            $("#waiting").show();
              $("#saveUser").attr({disabled:true}) ;
              var userName=$("input[name='userName']").val();
              var email=$("input[name='email']").val();
              var password=$("input[name='password']").val();
              var confirmPassword=$("input[name='confirmPassword']").val();
              var isNormal=$("input[name='isNormal']").val();
              if(userName=='Username' || email=='Email' || $('#password').attr('value') == '' || $('#confirmPassword').attr('value') == '') {
                    $("#saveUser").attr({disabled:false}) ;
                    alert("Please input all fields!!!");
                    $("#waiting").hide();
              } else {

                      if(isNormal=="false"){
                          alert("You can't save your data.There are some incorrect data!");
                           $("#saveUser").attr({disabled:false}) ;
                            $("#waiting").hide();
                      } else {
                            $.ajax({
                                  url: "addNewUser.action",
                                  data:{
                                      userName :  userName,
                                      email : email,
                                      password: password,
                                      confirmPassword: confirmPassword
                                  },
                                  type:"post",
                                  dataType: "json" ,
                                  success:function(data) {

                                      if(data.result!="") {
                                      if(data.result=="login"){
                                           window.location.href = 'main.action';
                                      }  else{
                                            {alert(data.result);}
                                            $("#waiting").hide();
                                            $("#saveUser").attr({disabled:false}) ;
                                          if(data.result.eq('SUCCESS')){
                                                      $("#addUser").hide("slow");
                                                   $('#grayBox').css("width", "0px");
                                                   $('#grayBox').css("height", "0px");
                                                  setTimeout(function(){
                                                       location.reload();
                                                  },1000) ;
                                          }


                                      }
                                  }
                                  }
                            });
                      }
              }
              ajaxLoading=false;
          }

          });


           $('li.user').click(function(){
              if(!ajaxLoading){
                   ajaxLoading=true;
                   var obj=$(".subUser");
                   var count= $(".subUser").find("li").length;
                   if(count==0){
                       $.ajax({
                          url:'adminUsersView.action',
                          type:'POST',
                               success:function(result){
                                   $("#allNetworks").attr("src",'images/users/users1.png')  ;
                                   obj.html(result);
                                   var networkHeightInt=parseFloat($("#user").css("height").split("p")[0]);
                                   var contentHeightInt=parseFloat($("#content").css("height").split("p")[0]);
                                   $("#content").css("height",contentHeightInt>networkHeightInt?contentHeightInt:networkHeightInt) ;
                                   contentHeightInt=parseFloat($("#content").css("height").split("p")[0]);
                                   contentHeightInt>600?$("#deviceInfo").find("img").css("margin-top","15%"):$("#deviceInfo").find("img").css("margin-top","0%") ;
                               }
                          });
                   } else {
                          var t= $(".subUser").find("input[name='isHidden']").val();
                          if($(".subUser").find("input[name='isHidden']").val()==1){
                                 $("#items").show();
                                 $("#allUsers").attr("src",'images/users/users1.png');
                                 var li=$(".subUser").find("li");
                                    li.each(function(){
                                    li.attr("disable","false");
                                 }) ;
                                $(".subUser").find("input[name='isHidden']").val(0);
                                var userId=$(".selecting").parent().find("input[name='userId']").val();
                                var deviceSerial=$("input[name='selectedUser']").val();
                                if(userId!=null){
                                       $.ajax({
                                              url: "viewUserInfo.action",
                                              data:"userId="+userId,
                                              type:"post",
                                              success:function(data) {
                                                  $("#deviceInfo").html(data);

                                                }
                                        });
                               }
                             } else {
                              $("#items").hide();
                              $("#allUsers").attr("src",'images/users/user2.png.png');
                              var li=$(".subUser").find("li");
                              li.each(function(){
                                  li.attr("disable","true");
                              }) ;
                              $(".subUser").find("input[name='isHidden']").val(1);
                          }
                          $("#deviceInfo").html("");
                          var networkHeightInt=parseFloat($("#networks").css("height").split("p")[0]);

                               $("#content").css("height",networkHeightInt>600?networkHeightInt:600) ;
                      }
                  ajaxLoading=false;
              }
           });



            var clicking=0;
            $(".eachUserName").live("click",function(){
                if(!ajaxLoading){
                     ajaxLoading=true;
                     clicking=1;
                     var item=$(this);
                     item.attr({disabled:true});
                     var allLi=$(this).parent().parent().find(".eachUserName").removeClass("selecting");
                     $(this).addClass("selecting") ;
                     var userId=$(this).parent().find("input[name='userId']").val();
                     $("#deviceInfo").html("");
                             $.ajax({
                                      url: "viewUserInfo.action",
                                      data:"userId="+userId,
                                      type:"post",
                                      success:function(data) {
                                         $("#deviceInfo").html(data);
                                           item.attr({disabled:false});
                                           $("input[name='selectedUser']").val("");
                                      }
                            });
                        ajaxLoading=false;
                }
               });

    });

</script>
<style type="text/css">

    #addUser {
        background-color: #aaaaaa;
        margin-top: -200px;
        margin-left: 250px;
        border: #555555 solid 3px;
        display: none;
        position: fixed;
        width: 400px;
        height: 400px;
        z-index: 100;
    }

    .removeUser img {
        border: none;
    }
    .subUser{
        float:left;
        padding-left:0;
    }

    #close {
        height: 24px;
        width: 400px;
        margin-top: 0px;

    }

    h3 {
        margin-top: 0px;
        margin-left: 100px;
        font-style: italic;
        font-size: 18px;
        margin-bottom: 40px;
    }

    #close a {
        float: right;
        margin-right: 0px;
        width: 24px;
    }

    #close a img {
        border: none;
    }
    .eachUserName{
       float:left;
       display: inline;
    }

    .add a {
        text-decoration: none;
        color: #212121;
    }



    .userName, .email, #fakepassword, #password, #confirmPassword, #fakeCnfPassword {
        margin-left: 100px;
        margin-bottom: 10px;
        float:left;
        width: 200px;
        height: 30px;
        text-align: center;
        font-style: italic;
        color: #555555 !important;
    }
    #validUsername,#validCnfPassword,#validEmail,#validPassword{
        margin-left: 100px;
        font-size: 15px;
        color: red;
        margin-top: 0px;
       width:200px;
        float:left;
    }

    .removeUser{
        float: right;
        margin-top: 5px;

    }


</style>
<div id="grayBox"></div>
<div id="waiting"></div>
<input type="hidden" value="<s:property value ='items' />" name="items"/>

<div id="addUser">

    <div id="close">

        <a href="#" class="closeWindow">
            <img src="<%=request.getContextPath()%>/images/close/close.png" width="24" height="24"/>
        </a>
    </div>
    <h3> Adding new user </h3>
        <span id="validUsername"></span>
    <input type="text" class="userName" name="userName" value="Username" />
        <span id="validEmail"></span>
    <input type="text" name="email" class="email" value="Email"/>

    <input style="color: #ccc" type="text" name="fakepassword" id="fakepassword" value="Password" onfocus="pwdFocus()"/>
     <span id="validPassword"></span>
    <input style="display: none" type="password" name="password" id="password" value="" onblur="pwdBlur()"/>

    <input style="color: #ccc" type="text" name="fakeCnfPassword" id="fakeCnfPassword" value="Confirm Password"
           onfocus="cnfPwdFocus()"/>
        <span id="validCnfPassword"></span>
    <input style="display: none" type="password" name="confirmPassword" id="confirmPassword" value=""
           onblur="cnfPwdBlur()"/>

    <input type ="hidden" name="isNormal" value="false"/>

    <input type="submit" value="Save" id="saveUser"
           style="margin-left: 120px;width: 80px;height:35px;margin-top:0px; float: left;"/>
    <input type ="reset" value="Cancel"  id="cancel"
           style="margin-left: 15px;width: 80px;height:35px;margin-top:0px; float: left;"/>
</div>
<div id="items">
    <s:if test="%{users!=null}">
        <s:iterator value="users" var="user" status="s_user">
            <li class="item">
                <div class="eachUserName">
                    <img src="<%=request.getContextPath()%>/images/users/user2.png" width="16" height="16"/>
                    <s:property value="#user.username"/>
                </div>
                <input type="hidden" value="<s:property value="#user.userId" />" name="userId"/>
                <s:if test="%{#session.user.userType.value==1}">
                    <a href="#" class="removeUser">
                        <img src="<%=request.getContextPath()%>/images/admin/remNetwork.png" width="12" height="12"
                             title="Remove user"/>
                         <input type="hidden" value="<s:property value="#user.username" />" name="userName"/>
                    </a>
                </s:if>
            </li>
        </s:iterator>
        <s:if test="%{#session.user.userType.value==1}">
            <li class="add">
                <img src="<%=request.getContextPath()%>/images/admin/addNetwork.png" width="16" height="16"
                     title="Add user"/>
                <a href="#">Add new</a>
            </li>
        </s:if>
        <input type="hidden" name="isHidden" value="0"/>
    </s:if>
    <s:else>
        <li class="add">
            <img src="<%=request.getContextPath()%>/images/admin/addNetwork.png" width="16" height="16"
                 title="Add user"/>
            <a href="#">Add new</a>
        </li>
    </s:else>
</div>

